# -*- coding: utf-8 -*-

# File Name： f5_domain_ip_fetch
# Description :
# Author : lirui
# create_date： 2022/9/5
# Change Activity:
import time

import ml
from ml.network.ip_utility.ip_re import is_ipv4, get_ipv4_str, get_ipv6_str
from ml.spider.selenium_utility import SeleniumUtility
from modules.internet_info_fetch.tmp import _get_domain


class F5DomainIPCollector:
    def __init__(self, url='https://196.2.2.28', login_info='admin/zyPkGGC*Y00', driver_path='resource/spider/geckodriver.exe'):
        self.username, self.password = self._parse_login_info(login_info)
        self.url = url
        self.driver_path = ml.join_relative_path(driver_path)
        self.selenium_utility = SeleniumUtility(driver_path=self.driver_path)

    @staticmethod
    def __get_login_button(elements):
        """

        Args:
            elements:

        Returns:

        """
        for e in elements:
            if e.text == 'Log in':
                return e
        raise Exception('Did not find login button.')

    def _login(self):
        """
        login the web and input username and password.
        Returns:

        """
        self.selenium_utility.open_page(self.url)
        self.selenium_utility.input_element_by_id('username', self.username)
        self.selenium_utility.input_element_by_id('passwd', self.password)
        elements = self.selenium_utility.find_elements(by='tag name', value='button')
        login_button_element = self.__get_login_button(elements)
        self.selenium_utility.click_element(login_button_element)

    def _turn_to_data_page(self):
        element = self.selenium_utility.find_element_by_id('mainmenu-statistics-statistics')
        self.selenium_utility.click_element(element)
        element = self.selenium_utility.find_element_by_id('pagemenu-dns')
        self.selenium_utility.click_element(element)
        element = self.selenium_utility.find_element_by_id('pagemenu-dns-gslb')
        self.selenium_utility.click_element(element)
        # switch to sub iframe.
        iframe_element = self.selenium_utility.find_element_by_id('contentframe')
        self.selenium_utility.switch_to_iframe(iframe_element)
        select_element = self.selenium_utility.find_elements_by_tag_name('select')[0]
        self.selenium_utility.click_element(select_element)
        options = select_element.find_elements(by="tag name", value='option')
        for opt in options:
            if opt.text.strip() == 'Pool Members'.strip():
                self.selenium_utility.click_element(opt)
                break
        # click all page.
        select = self.selenium_utility.find_elements_by_name('ptable')[0]
        options = select.find_elements(by="tag name", value='option')
        self.selenium_utility.click_element(options[-1])
        time.sleep(3)

    @staticmethod
    def _get_domain(line):
        items = line.split(' ')
        domain = items[2]
        return domain.split('_')[0]

    @staticmethod
    def _parse_html(info):
        """

        Args:
            info:

        Returns:

        """
        info_lst = []
        lines = info.split('\n')
        for line in lines:
            is_ip_line = False
            ip = ''
            if is_ipv4(line):
                is_ip_line = True
                ip = get_ipv4_str(line)
                ip = ip[0]
            elif len(get_ipv6_str(line)) > 0:
                is_ip_line = True
                ip = get_ipv6_str(line)
                ip = ip[0][0]
            if is_ip_line:
                domain = _get_domain(line)
                info_lst.append([ip, domain])
        return info_lst

    def _parse_info(self):
        """

        Returns:

        """
        table = self.selenium_utility.find_element_by_id('list_body')
        ip_domain_list = self._parse_html(table.text)
        return ip_domain_list

    def launch(self):
        self._login()
        self._turn_to_data_page()
        domain_ip_info = self._parse_info()
        self.selenium_utility.close()
        return domain_ip_info

    @staticmethod
    def _parse_login_info(login_info):
        """

        Args:
            login_info:

        Returns:

        """
        return login_info.strip().split('/')


def _main():
    collector = F5DomainIPCollector()
    collector.launch()


if __name__ == '__main__':
    _main()
